<template>
	<view v-show="contentFlag" class="content openWz-container">
		<!--  #ifdef  MP-WEIXIN -->
		<web-view :src="url"></web-view>
		<!--  #endif -->
		
		<!--  #ifdef  H5 -->
		<!-- <view class="title">提交身份认证信息</view>
		<view class="tip f-24">使用系统前需开通居民身份网络可信凭证（CTID）</view> -->
		
		<image class="camera-example" src="/static/images/camera_example.png"></image>
		<view class="f-24 camere-tip">拍摄时请露出五官以避免认证失败</view>

		<view ref="input" class="open-btn flexbox flexbox-middle flexbox-center f-32">
			<!-- <input type="file" accept="image/*" mutiple="mutiple" value="shagnchuan" /> -->
			<image class="small-camera" src="/static/images/small_camera.png"></image>
			开始拍摄
		</view>
		<!-- <image :src="preview"></image> -->
		<!--  #endif -->
		
	</view>

</template>

<script>
	//#ifdef H5
		var wx = require('../../static/js/wx_sdk/jweixin.js')
	//#endif
	import config from "../../request/config.js";
	var EXIF = require('../../static/js/exif.min.js')
	
	import { pushData } from '@/static/js/utils.js'
	export default {
		data() {
			return {
				url: '',
				curParam: {},
				preview: '',
				testdata: '',
				orientation: '',
				contentFlag: false
			}
		},
		onLoad: function() {
			let curPage = this.getCurPage();
			this.curParam = curPage.options || curPage.$route.query;
			//#ifdef MP
				this.url = `${config.BASEURL}/h5#/pages/openWz-step2/index?rurl=${this.curParam.rurl}&scan_flag=${this.curParam.scan_flag}&type=${this.curParam.type}&cardNum=${this.curParam.cardNum}&name=${this.curParam.name}&idcardAuthData=${this.curParam.idcardAuthData}&bsn=${this.curParam.bsn}&authorization=${uni.getStorageSync('authorization')}&cer_id=${this.curParam.cer_id}&id=${this.curParam.id}&phone=${this.curParam.phone}`
			//#endif
			
			//#ifdef H5
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				uni.setStorageSync('authorization', this.curParam.authorization);
			//#endif
			
		},
		mounted() {
			//#ifdef H5
			let that = this
			that.canvas = document.createElement('canvas')
			that.context = that.canvas.getContext('2d')
			that.$nextTick(function(){
				var input = document.createElement('input')
				input.style.width="100%";
				input.type = 'file'//添加file类型
				//input.multiple = 'multiple'// 可以选择多个
				input.accept="image/*" // 限制只能上传PDF文件，可以不限制，能上传任何类型
				input.capture="camera"
				input.style.height="100%";
				input.style.position="absolute";
				input.style.top="0";
				input.style.right="0";
				input.style.opacity="0";
				input.style.overflow="hidden"; //防止注意input 元素溢出
				input.id = 'file';
				var Orientation = null; 
				//that.$refs.input.$el.appendChild(input); // 这里可能会报$el找不到错误，所以加了延时器，报错的原因是this.$refs.input没有找到为null，所以需要等页面结构加载完后再将其添加进去
				that.timer = setInterval(() => {
					if(that.$refs.input.$el) {
						that.$refs.input.$el.appendChild(input);
						that.contentFlag = true
						uni.hideLoading();
						clearInterval(that.timer)
					}
				}, 100)
				
				input.onchange = function(event){
					var imgobj = new Image()
					var imgobj2 = new Image()
					var reader = new FileReader()
					
					const file = event.target.files[0];
					//图片方向角 added by lzk  
					//console.log(file)
					that.getImageTag(file, 'Orientation').then((res) => {
						//console.log(res)
						Orientation = res
						reader.readAsDataURL(file)
						reader.onload = (e) => {
							imgobj.src = e.target.result
							//this.cutImg = e.target.result
						}
						reader.onerror = () => {
						   //Toast("图片上传失败，麻烦稍后再试试~")
						}
					});
					
					imgobj.onload = () =>  {
						const originWidth = imgobj.width
						const originHeight = imgobj.height
						//图片压缩开始
						// 最大尺寸限制
						const maxWidth = 300, maxHeight = 300
						// 目标尺寸
						let targetWidth = originWidth, targetHeight = originHeight
						// 图片尺寸超过400x400的限制
						if (originWidth > maxWidth || originHeight > maxHeight) {
							if (originWidth / originHeight > maxWidth / maxHeight) {
								// 更宽，按照宽度限定尺寸
								targetWidth = maxWidth
								targetHeight = Math.round(maxWidth * (originHeight / originWidth))
							} else {
								targetHeight = maxHeight
								targetWidth = Math.round(maxHeight * (originWidth / originHeight))
							}
						}
						//_parent.find("img").css("width","100%")
						// canvas对图片进行缩放
						that.canvas.width = targetWidth
						that.canvas.height = targetHeight
						// 清除画布
						that.context.clearRect(0, 0, targetWidth, targetHeight)
						// 图片压缩
						that.context.drawImage(imgobj, 0, 0, targetWidth, targetHeight)
						var base64Code2 = that.canvas.toDataURL('image/jpeg', 1)
						//that.preview =base64Code2
						imgobj2.src = base64Code2
					}
					
					imgobj2.onload = () =>  {
						//alert(Orientation)
						that.orientation = Orientation 
						//如果方向角不为1，都需要进行旋转 added by lzk  
						if (that.isIos13() < 13.0) {
							if(Orientation != "" && Orientation != 1){  
								//alert('旋转处理');  
								switch (Orientation) {
								case 6: // 顺时针旋转90度
									that.rotateImg(imgobj2, 'right', that.canvas);
									break;
								case 8: // 逆时针旋转90度
									that.rotateImg(imgobj2, 'left', that.canvas);
									break;
								case 3: // 顺时针旋转180度
									that.rotateImg(imgobj2, 'right', that.canvas, 2);
									break;
								default:
									break;
								}         
							}
						}
						that.preview = that.canvas.toDataURL('image/jpeg', 1)
						var imgBase = that.preview.split(',')[1];
						let param = {
							bsn: decodeURIComponent(that.curParam.bsn),
							photoData: imgBase,
							name: that.curParam.name,
							idNo: that.curParam.cardNum,
							idcardAuthData: decodeURIComponent(that.curParam.idcardAuthData)
						}
						that.upload(param)
					}
					
				}
		
			})
			//#endif
		
		},
		methods: {
			getImageTag (file, tag){
			    if (!file) return 0;
			    return new Promise((resolve, reject) => {
			        /* eslint-disable func-names */
			        // 箭头函数会修改this，所以这里不能用箭头函数
			        EXIF.getData(file, function () {
			            const o = EXIF.getTag(this, tag);
			            resolve(o);
			        });
			    });
			},
			// 苹果手机ios13以上和13以下
			isIos13() {
				var str= navigator.userAgent.toLowerCase(); 
				    var ver=str.match(/cpu iphone os (.*?) like mac os/);
				    if(!ver){
				        return 0
				    }else{
						return parseFloat(ver[1].replace(/_/g,"."))
				    }
			},
			upload(param) {
				let that = this
				uni.showLoading({
				    title: '请求中...'
				});
				this.$HTTP.post('/audit/user', param, false, false, true).then((res) => {
					let ctid = res.data.ctid
					pushData()
					uni.hideLoading();
					if(that.curParam.rurl && that.curParam.rurl != 'undefined') {
						wx.miniProgram.getEnv(function(res2) {
						    wx.miniProgram.redirectTo({  
						    	url: `${that.curParam.rurl}?ctid=${ctid}`
						    })  
						})
					} else if(that.curParam.type === 'certificateCode' ) {
						wx.miniProgram.getEnv(function(res2) {
						    wx.miniProgram.redirectTo({  
						    	url: `/pages/certificateCode/index?id=${that.curParam.id}&ctid=${ctid}`
						    })  
						})
					} else if(that.curParam.type === 'wzcard') {
						wx.miniProgram.getEnv(function(res2) {
						    wx.miniProgram.redirectTo({  
						    	url: `/pages/wzcard/index?ctid=${ctid}`
						    })  
						})
					} else if(that.curParam.type === 'companyAuth') {
						wx.miniProgram.getEnv(function(res2) {
						    wx.miniProgram.redirectTo({  
						    	url: `/pages/companyAuth/index?scan_flag=${that.curParam.scan_flag}&ctid=${ctid}`
						    })  
						})
					} else if(that.curParam.type === 'getCertificate'){
						wx.miniProgram.getEnv(function(res2) {
						    wx.miniProgram.redirectTo({  
						    	url: `/pages/getCertificate/index?id=${that.curParam.id}&phone=${that.curParam.phone}&ctid=${ctid}`
						    })  
						})
					} else if(that.curParam.type === 'applyCertificate'){
						wx.miniProgram.getEnv(function(res2) {
						    wx.miniProgram.redirectTo({  
						    	url: `/pages/applyCertificate/index?template_id=${that.curParam.id}&ctid=${ctid}`
						    })  
						})
					} else if(that.curParam.type ==='authOperation') {
						that.bindCompany(that.curParam.id)
						wx.miniProgram.getEnv(function(res2) {
						    wx.miniProgram.reLaunch({  
						    	url: `/pages/authStatus/index?type=1&ctid=${ctid}`
						    })  
						})
					} else {
						wx.miniProgram.getEnv(function(res2) {
						    wx.miniProgram.reLaunch({  
						    	url: `/pages/authStatus/index?type=1&ctid=${ctid}`
						    })  
						})
					}
				}).catch((err) => {
					if (err.code == '220002' || err.code == '220001' ) {
						uni.hideLoading();
						wx.miniProgram.getEnv(function(res2) {
							if(that.type) {
								wx.miniProgram.redirectTo({
									url: `/pages/openWz-step3/index?id=${err.data.id}&type=${that.curParam.type}&commonId=${that.curParam.id}&scan_flag=${that.curParam.scan_flag}&rurl=${that.curParam.rurl}&phone=${that.curParam.phone}`
								}) 
							} else {
								wx.miniProgram.navigateTo({
									url: `/pages/openWz-step3/index?id=${err.data.id}&type=${that.curParam.type}&commonId=${that.curParam.id}&scan_flag=${that.curParam.scan_flag}&rurl=${that.curParam.rurl}&phone=${that.curParam.phone}`
								}) 
							}
							 
						})
						return false
					}
					
					if (err.code == '220003') {
						uni.showToast({
						    title: '已冻结需要去官方app解冻',
						    icon: 'none'
						})
						
					}
					setTimeout(() => {
						uni.hideLoading();
						wx.miniProgram.getEnv(function(res2) {
						    wx.miniProgram.reLaunch({  
						    	url: `/pages/authStatus/index?type=2&msg=${err.msg}&id=${that.curParam.id}&authtype=${that.curParam.type}&scan_flag=${that.curParam.scan_flag}&rurl=${that.curParam.rurl}&phone=${that.curParam.phone}`
						    })  
						})
					}, 2000)
					
				}) 
			},
			getCurPage(){
			    let pages = getCurrentPages();
			    let curPage = pages[pages.length-1];
			    return curPage
			},
			bindCompany(company_id) {
				let param = {
					company_id: company_id
				}
				this.$HTTP.post('/user/binded', param, true).then((res) => {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}).catch((err) => {
					
				})
			},
			 //对图片旋转处理 added by lzk  
			rotateImg (img, dir = 'right', canvas, s = 1){
			    const MIN_STEP = 0;
			    const MAX_STEP = 3;
			
			    const width = canvas.width || img.width;
			    const height = canvas.height || img.height;
			    let step = 0;
			
			    if (dir === 'right') {
			        step += s;
			        step > MAX_STEP && (step = MIN_STEP);
			    } else {
			        step -= s;
			        step < MIN_STEP && (step = MAX_STEP);
			    }
			
			    const degree = step * 90 * Math.PI / 180;
			    const ctx = canvas.getContext('2d');
			
			    switch (step) {
			    case 1:
			        canvas.width = height;
			        canvas.height = width;
			        ctx.rotate(degree);
			        ctx.drawImage(img, 0, -height, width, height);
			        break;
			    case 2:
			        canvas.width = width;
			        canvas.height = height;
			        ctx.rotate(degree);
			        ctx.drawImage(img, -width, -height, width, height);
			        break;
			    case 3:
			        canvas.width = height;
			        canvas.height = width;
			        ctx.rotate(degree);
			        ctx.drawImage(img, -width, 0, width, height);
			        break;
			    default:
			        canvas.width = width;
			        canvas.height = height;
			        ctx.drawImage(img, 0, 0, width, height);
			        break;
			    }
			}
		}


	}
</script>

<style lang="scss" scoped>
	@import "../openWz-step1/index.scss";
</style>
